package swing;

import cz.muni.fi.pv168.ContactManager.DBUtil;
import cz.muni.fi.pv168.ContactManager.Person;
import cz.muni.fi.pv168.ContactManager.PersonManagerImpl;

import javax.swing.*;
import java.awt.event.*;

public class AddPerson extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField firstNameText;
    private JTextField lastNameText;

    private Person person;
    private PersonManagerImpl personManager = new PersonManagerImpl();

    public AddPerson(Person person) {
        if (person!=null) {
            this.person = person;
            firstNameText.setText(person.getFirstName());
            lastNameText.setText(person.getLastName());
        }
        
        
        personManager.setDataSource(DBUtil.getDataSource());
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

// call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    public AddPerson() {
        this(null);
    }

    private void onOK() {
        if(firstNameText.getText()!="" || firstNameText.getText()!=null || lastNameText.getText()!="" || lastNameText.getText()!=null ){
            if (person==null) person = new Person();
            person.setFirstName(firstNameText.getText());
            person.setLastName(lastNameText.getText());
            if(person.getId()==null) personManager.createPerson(person);
                    else personManager.updatePerson(person);
        }
        dispose();
    }

    private void onCancel() {
// add your code here if necessary
        dispose();
    }
}
